<template>
	<view class="padding">
		<u-cell-group class="padding-top">
			<u-cell title="头像" @click="showEditPopup">
				<u-avatar slot="value" size="70px" :src="userInfo.avatarUrl"></u-avatar>
			</u-cell>
			<u-cell title="昵称" :value="userInfo.username" @click="showEditPopup" />
			<u-cell title="性别" :value="userInfo.gender" @click="showEditPopup" />
			<u-cell title="简介" :value="userInfo.description" @click="showEditPopup" />
		</u-cell-group>

		<u-popup :show="show" round="15" mode="center" @close="closePopup">
			<view class="padding">
				<u-form>
					<u-form-item label="头像">
						<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="1"
							:previewFullImage="true" :maxCount="1"></u-upload>
					</u-form-item>
					<u-form-item label="昵称">
						<u-input v-model="editInfo.username" placeholder="请输入昵称" />
					</u-form-item>
					<u-form-item label="性别">
						<u-radio-group v-model="editInfo.gender">
							<u-radio name="1">男</u-radio>
							<u-radio name="2">女</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label="简介">
						<u-input type="textarea" v-model="editInfo.description" placeholder="请输入简介" />
					</u-form-item>
					<u-button type="primary" formType="submit" @click="submitEdit()">保存</u-button>
				</u-form>
			</view>
			
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userId: null,
				userInfo: {
					avatarUrl: '',
					username: '',
					gender: 1,
					description: ''
				},
				show: false,
				editInfo: {
					avatarUrl: '',
					username: '',
					gender: 1,
					description: ''
				},
				fileList: []
			}
		},
		onLoad(option) {
			this.userId = uni.getStorageSync('userId');
			this.getUserById();
		},
		methods: {
			getUserById() {
				uni.request({
					url: 'http://localhost:8083/user/' + this.userId,
					success: (res) => {
						this.userInfo = res.data;
						this.editInfo = {
							...this.userInfo
						};
					},
					fail: (err) => {
						console.log(err);
					}
				});
			},
			showEditPopup() {
				this.show = true;
				this.editInfo = {
					...this.userInfo
				};
				this.fileList = [{
					url: this.userInfo.avatarUrl
				}];
			},
			closePopup() {
				this.show = false;
				this.fileList = [];
			},
			handleAvatarUpload(response) {
				// 假设服务器返回新的头像URL
				this.editInfo.avatarUrl = response.url;
				uni.showToast({
					title: '头像更新成功',
					icon: 'success',
				});

			},
			beforeUpload(file) {
				// 上传前的钩子，可以在这里进行图片压缩等操作
				// 返回 false 可以阻止上传
				return true;
			},
			submitEdit() {
				console.log('保存按钮被点击');
				uni.request({
					url: `http://localhost:8083/user/updateUser/${this.userInfo.userId}`,
					method: 'PUT',
					data: this.editInfo,
					success: (res) => {
						this.userInfo = {
							...this.editInfo
						};
						 // 如果需要，重新获取数据以刷新页面显示
						this.getUserById();
						this.closePopup();
						uni.showToast({
							title: '修改成功',
							icon: 'success'
						});
						uni.reLaunch({
						    url: '/pages/my/my'
						})
						// if (res.statusCode === 200) {
							
						// }
					},
					fail: (err) => {
						console.log(err);
					}
				});
			},
			// 删除图片
			deletePic(event) {
			    if (Array.isArray(this.fileList)) {
			      this.fileList.splice(event.index, 1);
			    }
			  },
			 async afterRead(event) {
			    let lists = [].concat(event.file);
			    let fileList = this.fileList;
			    lists.forEach((item) => {
			      fileList.push({
			        ...item,
			        status: 'success',
			        message: '上传成功'
			      });
			    });
			    for (let i = 0; i < lists.length; i++) {
			      const result = await this.uploadFilePromise(lists[i].url);
			      let item = fileList[fileList.length - 1];
			      fileList.splice(fileList.length - 1, 1, {
			        ...item,
			        status: 'success',
			        message: '',
			        url: result
			      });
			    }
			  },
			  // 上传文件的 Promise 方法
			  uploadFilePromise(url) {
			    return new Promise((resolve, reject) => {
			      uni.uploadFile({
			        url: `http://localhost:8083/user/updateAvatar/${this.userInfo.userId}`,
			        filePath: url,
			        name: 'avatarUrl',  
			        success: (res) => {
						console.log('修改头像成功')
			          setTimeout(() => {
			            resolve(res.data.data);
			          }, 1000);
			        },
			        fail: (err) => {
			          reject(err);
			        }
			      });
			    });
			  },
		}
	}
</script>
<style>

</style>